package myself.a010BinaryTreeRecursion;

/**
 * @author 叶之越
 * Description
 * Date 2021/1/27
 * Time 22:26
 * Mail 739153436@qq.com
 */
public class MaxSubBSTSize {
    public static Info process(Node random) {
        if (random == null) {
            return null;
        }
        Info leftInfo = process(random.left);
        Info rightInfo = process(random.right);


        int min = random.value;
        int max = random.value;

        if (leftInfo != null) {
            min = Math.min(min, leftInfo.min);
            max = Math.max(max, leftInfo.max);
        }
        if (rightInfo != null) {
            min = Math.min(min, rightInfo.min);
            max = Math.max(max, rightInfo.max);
        }


        int maxSubBSTSize = 0;
        if (leftInfo != null) {
            maxSubBSTSize = leftInfo.maxSubBSTSize;
        }
        if (rightInfo != null) {
            maxSubBSTSize = Math.max(maxSubBSTSize, rightInfo.maxSubBSTSize);
        }
        boolean isAllBST = false;


        if (
            // 左树整体需要是搜索二叉树
                (leftInfo == null ? true : leftInfo.isAllBST)
                        &&
                        (rightInfo == null ? true : rightInfo.isAllBST)
                        &&
                        // 左树最大值<x
                        (leftInfo == null ? true : leftInfo.max < random.value)
                        &&
                        (rightInfo == null ? true : rightInfo.min > random.value)
        ) {
            maxSubBSTSize =
                    (leftInfo == null ? 0 : leftInfo.maxSubBSTSize)
                            +
                            (rightInfo == null ? 0 : rightInfo.maxSubBSTSize)
                            +
                            1;
            isAllBST = true;
        }
        return new Info(isAllBST, maxSubBSTSize, min, max);
    }

    // 任何子树
    public static class Info {
        public boolean isAllBST;
        public int maxSubBSTSize;
        public int min;
        public int max;

        public Info(boolean is, int size, int mi, int ma) {
            isAllBST = is;
            maxSubBSTSize = size;
            min = mi;
            max = ma;
        }
    }

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

}
